<template>
  <div class="seni">
    <el-popover
      placement="bottom-start"
      :width="isWeb ? '125' : '115'"
      trigger="click"
    >
      <div class="select-status" v-if="idx != 3" v-for="(item,idx) in statusArr" :key="idx" @click="selectStatus(idx,item)">
        <el-button :type="item.type" :icon="item.icon" circle></el-button>
        <span>{{item.text}}</span>
      </div>
      <span slot="reference">
                <el-button
                  :type="currentStatus.type"
                  :icon="currentStatus.icon"
                  circle></el-button>
                <i style="cursor: pointer;" class="el-icon-arrow-down"></i>
            </span>
    </el-popover>
    <span class="statusText">{{ currentStatus.text }}</span>
    <span class="customerName">{{ updateInfo.name }}</span>
    <span class="role">{{ updateInfo.roleId == 7 ? '高级客服' : '未知'}}</span>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <child-text title="客户ID" :value="transforData.customerId" :xs='24'/>
        <child-text title="客户名称" :value="transforData.customerName"/>
        <child-text title="性别" :value="transforData.sex"/>
        <child-text title="行业" :value="transforData.industryName" :xs='24'/>
        <child-text title="手机号" :value="transforData.phone" :xs='24'/>
        <child-text title="标签" :value="transforData.word" isslot :xs="24" :sm="12">
          <template slot-scope="info">
            <el-tag style="margin-right:8px;" v-for="t in info.data" :key='t' type="danger">
              {{ t }}
            </el-tag>
          </template>
        </child-text>
        <child-text title="关键词" :value="transforData.label" isslot :xs="24" :sm="12">
          <template slot-scope="info">
            <el-tag style="margin-right:8px;" v-for="t in info.data" :key='t' type="danger">
              {{ t }}
            </el-tag>
          </template>
        </child-text>
      </div>
      <el-row :gutter="20">

        <el-form :rules="userEditRules" :model="pushInfo" ref="userForm">
          <div>
            <el-form-item label="姓名" prop="customerName" placeholder="请输入客户姓名" label-width="55px">
              <el-col :xs='24' :sm='10'>
                <el-input type="text" v-model.trim="pushInfo.customerName"></el-input>
              </el-col>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="电话" prop="phone" placeholder="请输入电话号码" label-width="55px">
              <el-col :xs='24' :sm='10'>
                <el-input type="text" v-model.trim="pushInfo.phone"></el-input>
              </el-col>
            </el-form-item>
          </div>
          <el-form-item label="性别" label-width="55px">
            <el-col :xs="24">
              <el-radio-group v-model="pushInfo.sex">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item label="意向" label-width="55px">
            <el-col :xs="24" :sm="20">
              <el-checkbox-group v-model="pushInfo.item" size="mini">
                <el-checkbox-button v-for="tag in tags" :label="tag" :key="tag">{{tag}}</el-checkbox-button>
              </el-checkbox-group>
            </el-col>

          </el-form-item>
          <el-form-item label="备注" prop="remark" label-width="55px">
            <el-col :xs="24" :sm='14'>
              <el-input :rows="3" type="textarea" v-model.trim="pushInfo.remark" placeholder="请输入内容"></el-input>
            </el-col>

          </el-form-item>
          <el-form-item label-width="55px">
            <el-col :xs="24">
              <el-button type="primary" @click="subHander" :loading="false">提交</el-button>
              <el-button @click="resetForm">取消</el-button>
            </el-col>

          </el-form-item>
        </el-form>
      </el-row>

    </el-card>

    <audio ref="toast" src="/static/audio/toast.mp3" hidden></audio>
  </div>
</template>

<script>
  import childText from "./childText.vue";
  import {callvip} from "@/api/highServer";
  import {parseTime} from "@/utils/index";
  import {mapGetters} from 'vuex'

  export default {
    data() {
      const CheckTel = (rule, value, callback) => {
        let tempValue = value * 1;
        if (!Number.isInteger(tempValue)) {
          callback(new Error("电话号码必须是数字"));
        } else if ( tempValue && tempValue.toString().length != 11) {
          callback(new Error("电话号码必须是11位"));
        } else {
          callback();
        }
      };
      const nameCheck = function (rule, value, callback) {
        var regex = /^[\u4E00-\u9FA5A-Za-z0-9]+$/;
        if (!value) {
          callback(new Error("请输入客户名称"))
        } else if (!regex.test(value)) {
          callback(new Error("请不要输入特殊字符！"));
        } else {
          callback();
        }
      }
      return {
        tags: ['无意向', '有意向', '不排斥', '再联系', '已对接'],
        timer: null,
        isWeb: true,
        websocket: null,
        //验证的规则的key 必须与 绑定的 key 相同，否则会失败，或返回的key是undefined
        pushInfo: {
          sex:'',
          phone:'',
          customerName:'',
          item: []
        },
        userEditRules: {
          customerName: [{required: true, validator: nameCheck, trigger: "blur"}],
          phone: [{required: false, validator: CheckTel, trigger: "blur"}]
        },
        transforData: {},
        statusArr: [
          {
            status: "online",
            type: "success",
            icon: "el-icon-service",
            text: "在线"
          },
          {
            status: "busyness",
            type: "warning",
            icon: "el-icon-phone-outline",
            text: "忙碌"
          },
          {status: "leave", type: "danger", icon: "el-icon-info", text: "离开"},
          {status: "offline", type: "info", icon: "el-icon-time", text: "离线"}
        ],
        currentStatus: {
          status: "online",
          type: "success",
          icon: "el-icon-service",
          text: "在线"
        }
      };
    },
    computed: {
      ...mapGetters([
        'updateInfo'
      ]),
      formLabelWidth() {
        return this.isWeb ? "80px" : "55px";
      }
    },
    components: {
      childText
    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      $route(to, from) {
        if (to.path === "/seni/index") {
          console.log('status :', this.websocket.readyState);
          !this.websocket && this.initWebSocket();
        }


      },
      // currentStatus(val) {
      //   if (val.status !== 'online' || val.status !== 'offline') {
      //
      //   }else {
      //     console.log('状态变更了，清理timer')
      //     clearInterval(this.timer);
      //     this.timer = null;
      //   }
      // }
    },
    methods: {
      setIntervalEvent() {
        if( this.timer ){
          return
        }
        this.timer = setInterval(() => {
          this.websocket.readyState !== 3 && this.threadPoxi(true)
          console.log("==== 心跳 ====")
        }, 10 * 1000)
      },
      getSendData() {
        return {
          userId: this.updateInfo.userId,
          status: this.currentStatus.status,
          companyId: this.updateInfo.companyId,
          name: this.updateInfo.name,
          phone: this.updateInfo.phone
        }
      },
      selectStatus(idx, item ,flag) {
        console.log('item',item)
        if (idx == 1 && !flag) {
          this.$message.error('不能主动切换忙碌状态')
          return;
        }   //不能手动点击切换为繁忙
        if(!flag && this.currentStatus.status == 'busyness'){
          this.$message.error('当前在忙碌状态，不能手动切换')
          return
        }
        this.currentStatus = this.statusArr[idx]

        if (item.status === 'online' || item.status === 'offline') {
          console.log('123')
          let temp = flag || false
          this.threadPoxi(temp,function () {
            this.setIntervalEvent();
          }.bind(this))
        } else {
          this.threadPoxi(flag)
        }
      },
      socketClose(){
        this.selectStatus(3,this.statusArr[3],true)
        this.timer && clearInterval(this.timer);
        this.websocket && this.websocket.readyState == 1 && this.websocket.close();
        return '确认关闭当前页面？'
      },
      threadPoxi(flag,cb) {  //flag 为真的时候  是不需要手动去 init socket
        if (!this.websocket) {
          console.log("初始化")
          this.initWebSocket();
          return;
        }
        // 实际调用的方法
        //参数
        let agentData = this.getSendData();

        console.log('websocket.readyStat', this.websocket.readyState);
        //若是ws开启状态
        if (this.websocket.readyState === this.websocket.OPEN) {
          this.websocketsend(agentData);
          cb && cb()
        } else if (this.websocket.readyState === this.websocket.CONNECTING) {
          // 若是 正在开启状态，则等待300毫秒
          let that = this; //保存当前对象this
          setTimeout(function () {
            that.websocketsend(agentData);
            cb && cb()
          }, 300);
        } else {
          if (!flag) {
            // 若未开启 ，则等待500毫秒
            this.initWebSocket();
            let that = this; //保存当前对象this
            setTimeout(function () {
              that.websocketsend(agentData);
              cb && cb()
            }, 500);
          }
        }
      },
      initWebSocket() {
        //初始化weosocket
        //ws地址
        // const wsuri = "ws://112.65.184.33:38090/ws";   //测试
        const wsuri = "ws://112.65.184.33:38088/ws";   //生产
        this.websocket = new WebSocket(wsuri);
        window.websocket = this.websocket;
        this.websocket.onmessage = this.websocketonmessage;
        this.websocket.onopen = this.websocketonopen;
        this.websocket.onclose = this.websocketclose;
        this.websocket.onerror = this.websocketerror;

        this.$router.afterEach((to,from) => {
          if(to.fullPath == "/search/index" || to.fullPath == "/seni/index"){
            console.log("=== 在该在的页面内跳转 ===")
          }else {
            console.log('=== 离开了页面 ===')
            this.socketClose()
          }
          // this.currentStatus = this.statusArr[2]; //设置为离开状态
          // this.websocket.close();
          // this.socketClose()
        });
      },
      websocketonopen() {
        console.log("=== open ===")
        //连接建立之后执行send方法发送数据
        let agentData = this.getSendData()
        this.websocketsend(agentData)
      },
      websocketonmessage(e) {
        //数据接收1
        try {
          console.log(e.data)
          if(JSON.parse(e.data).code == '200'){
            return
          }
          this.transforData = JSON.parse(e.data)
          this.selectStatus(1,this.statusArr[1],true) // 设置为繁忙状态
          // 赋值 默认值
          this.pushInfo['customerName'] = this.transforData['customerName']
          this.pushInfo['phone'] = this.transforData['phone']
          this.pushInfo['sex'] = this.transforData['sex']
          //播放提示音
          this.playToast()
          //震动
          this.vibration()
          //关闭
          // this.socketClose()
        } catch (e) {
          this.transforData = {}
        }
        console.log(this.transforData)
      },
      websocketsend(agentData) {
        console.log('agentData',agentData)
        if(!this.timer && agentData.status == 'online'){
          this.setIntervalEvent();
        }
        //数据发送
        this.websocket.readyState == this.websocket.OPEN && this.websocket.send(JSON.stringify(agentData));
      },
      websocketclose(e) {
        //关闭
        console.log("connection closed (" + e.code + ")");
        this.timer && clearInterval(this.timer);
        this.selectStatus(0,this.statusArr[0],false);

      },
      websocketerror(e) {
        console.log("error :" + JSON.stringify(e))
        this.socketClose()
      },
      resetForm() {
        this.$refs['userForm'].resetFields();
        this.pushInfo = {item: [],phone:'', customerName:'',sex:''}
      },
      subHander() {
        this.$refs["userForm"].validate(valid => {
          if (!valid) {
            this.$message.error("修改失败,请确认您的信息后再提交");
            return;
          }
          let tempData = Object.assign({}, this.pushInfo,
            {
              serviceId: this.updateInfo.userId,
              customerId: this.transforData.customerId,
              callTime: parseTime(new Date())
            }
          )
          callvip(tempData).then(res => {
            this.$message.success("提交成功");
            this.pushInfo = {item: [],phone:'', customerName:'',sex:''};
            this.transforData = {};
            setTimeout(() => {
              this.selectStatus(0, this.statusArr[0],true);  //提交完成后设置成 在线
            }, 1500)
          }).catch(res => {
            this.$message.error(res);
          })
        })
      },
      playToast() {
        this.$refs.toast.volume = 1;
        this.$refs.toast.play();
      },
      vibration() {
          navigator.vibrate = navigator.vibrate
                  || navigator.webkitVibrate
                  || navigator.mozVibrate
                  || navigator.msVibrate;

          if (navigator.vibrate) {
              // 支持
              console.log("支持设备震动！");
              navigator.vibrate([500, 300, 400,300]);
          }
      }
    },
    created() {
      this.initWebSocket()
      this.isWeb = window.innerWidth > 479 ? true : false
    },
    mounted(){
      // window.onbeforeunload= function(event) { return confirm("确定离开此页面吗？"); }
      var self = this;
      window.onbeforeunload = function (e) {
        var confirmationMessage = '确定离开此页面吗？';

        (e || window.event).returnValue = confirmationMessage;     // Gecko and Trident
        return confirmationMessage;                                // Gecko and WebKit
      };

      window.onunload = function (e) {
        this.websocket.readyState == this.websocket.OPEN && this.websocket.send(JSON.stringify({status:'offline'}));
      };
    },
    destroyed() {
      this.socketClose()
    }
  };
</script>
<style type="text/scss" lang="scss" scoped>
  .seni {
    .box-card {
      .el-card__header {
        padding: 5px;
      }
      min-width: 300px;
      max-width: 750px;
      margin-top: 15px;
    }
    .statusText {
      font-size: 14px;
      position: relative;
      top: 10px;
      color: #999;
    }
    .customerName {
      margin-left: 15px;
      font-size: 24px;
    }
    .role {
      margin-left: 10px;
      font-size: 12px;
      color: #999;
    }
  }

  @media (max-width: 479px) {
    .seni {
      .box-card {
        font-size: 14px;
      }
    }
  }
</style>
